package com.sf.innovate.hammer.game.net.http.interceptor

import okhttp3.Interceptor
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody

class ErrorHandleInterceptor : Interceptor {

  override fun intercept(chain: Interceptor.Chain): Response {

    try {
      val request = chain.request()
      // 服务器处理异常
      val res =  chain.proceed(request)
      if (!res.isSuccessful) {
        throw RuntimeException("server: ${res.message}")
      }
      return res
    } catch (e: Exception) {
      val body = ResponseBody.create(null, "1")
      return Response.Builder()
        .request(chain.request())
        .protocol(Protocol.HTTP_1_1)
        .message(e.message ?: "client internal error")
        .body(body)
        .code(200)
        .build()
    }
  }
}